<?php
	class Countries {

		function __construct(){
			FunctionsHelper::includeFiles(
				array(
					ADMINISTRATOR_MODEL_DIRECTORY . 'model.php',
					ADMINISTRATOR_MODEL_DIRECTORY . 'country.php'
				)
			);
		}

		public function getAll(){
			$arrCountries = array();
			$arrResult = Country::getAll();
			foreach($arrResult as &$country){
				$arrCountries[] = new Country($country);
			}
			return $arrCountries;
		}
		
		public function getAllActive(){
			$arrCountries = array();
			$arrResult = Country::getAllActive();
			foreach($arrResult as &$country){
				$arrCountries[] = new Country($country);
			}
			return $arrCountries;			
		}

		public function getCountry($arrInitialValue = null){
			if (empty($arrInitialValue))
				return new Country();

			$country = new Country($arrInitialValue);

			$country = $country->getCountry();
			if (empty($country))
				return new Country();
			
			return new Country($country[0]);
		}

		public function deleteCountry($countryId){
			$country = $this->getCountry(
				array(
					'country_id' => $countryId
				)
			);
			return $country->delete();
		}
		
		public function createCountry($arrInitialValues = null){			
			if (empty($arrInitialValues))
				return array();

			$arrInitialValues['files']['name'] = FunctionsHelper::filesFormatName(utf8_decode($arrInitialValues['files']['name']));
			$arrInitialValues['flag'] = $arrInitialValues['files']['name'];

			$country = new Country($arrInitialValues);

			$country->create();
			$this->updateFlag($arrInitialValues, 0);
			return 1;
		}

		public function updateCountry($arrCountry){
			if (!empty($arrCountry['eliminar']))
				$this->deleteFlag($arrCountry);
			$country = new Country($arrCountry);
			$this->updateFlag($arrCountry);
			$country->update();
			return 1;
		}

		private function deleteFlag($arrCountry){
			if (isset($arrCountry['eliminar'])){				
				$country = $this->getCountry($arrCountry);
				$country->deleteFlag();
				$country->setFlag('');
				$country->updateFlag();
			}
		}

		private function updateFlag($arrCountry, $updateDB = 1){
			if (isset($arrCountry['files']['tmp_name']) && !empty($arrCountry['files']['tmp_name'])){
				$arrCountry['flag'] = $arrCountry['files']['name'];

				copy($arrCountry['files']['tmp_name'], MAIN_IMAGES_FLAG_DIRECTORY . $arrCountry['files']['name']);
				if ($updateDB){
					$country = new Country($arrCountry);
					$country->updateFlag();
				}
			}	
		}
		
		
		public function activateCountry($id){
			$country = new Country(
				array (
					'country_id' => $id
				)
			);
			
			return $country->activate();
		}
	}
?>